package cn.passlink.bletoothchat.Adapter;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

import cn.passlink.bletoothchat.Entity.Friends;
import cn.passlink.bletoothchat.Entity.Groups;
import cn.passlink.bletoothchat.R;
import cn.passlink.bletoothchat.SqlTables.MyDatabaseHelper;
import cn.passlink.bletoothchat.mActivity.FriendTalkingActivity;
import cn.passlink.bletoothchat.mActivity.GroupTalkingActivity;

public class GroupsAdapter extends BaseAdapter {
    private Context context;
    private List<Groups> groupsList;
    private SQLiteDatabase database;
    private MyDatabaseHelper databaseHelper;


    private List<Groups> data;  // 定义数据源列表变量

    public GroupsAdapter(Context context, List<Groups> groupsList) {
        this.context = context;
        this.groupsList = groupsList;

        // 初始化数据库辅助类
        databaseHelper = new MyDatabaseHelper(context,2);
        // 获取可写入的数据库实例
        database = databaseHelper.getWritableDatabase();
    }

    @Override
    public int getCount() {
        return groupsList.size();
    }

    @Override
    public Object getItem(int position) {
        return groupsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.groups_item, parent, false);
            holder = new ViewHolder();
            holder.groupnameTextView = convertView.findViewById(R.id.group_name_TextView);
            holder.groupidTextView = convertView.findViewById(R.id.group_id_TextView);
            holder.membersAmountTextView = convertView.findViewById(R.id.group_members_TextView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Groups groups = groupsList.get(position);
        holder.groupnameTextView.setText( groups.getGroupname());
        holder.groupidTextView.setText("ID:"+groups.getGroupid());
        holder.membersAmountTextView.setText("all:"+groups.getMembers_amount());
        holder.Del=convertView.findViewById(R.id.groups_item_del);
        holder.Connect=convertView.findViewById(R.id.groups_item_connect);

        holder.Del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Groups mGroups = groupsList.get(position);
                String group_id = mGroups.getGroupid(); // 获取电话号码
                //先删除表
                String[] columns = {"group_table_name"};
                String selection = "group_id=?";
                String[] selectionArgs = {String.valueOf(group_id)};
                Cursor cursor = database.query("groups", columns, selection, selectionArgs, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int groupnameIndex = cursor.getColumnIndex("group_table_name");

                    if (groupnameIndex != -1) {
                        String group_table_name = cursor.getString(groupnameIndex);

                        // 执行操作，例如打印或使用 groupName

                        database.execSQL("DROP TABLE IF EXISTS `" + group_table_name + "`");
                    } else {
                        // 处理未找到 "groupname" 列的情况
                    }
                }
                if (cursor != null) {
                    cursor.close();
                }
//再删除记录
                String whereClause = "group_id = ?";
                String[] whereArgs = {group_id};
                int rowsAffected = database.delete("groups", whereClause, whereArgs);

                Log.d("Delete", "Rows deleted: " + rowsAffected);
// 更新数据源列表
                // 重新设置适配器
                if (rowsAffected > 0) {
                    groupsList.remove(position);
                    notifyDataSetChanged();
                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                    // 更新数据源列表


                }

            }
        });

        holder.Connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理Connect按钮的点击事件
                // 编写您想要执行的代码逻辑
                Groups mGroups = groupsList.get(position);
                // 处理Connect按钮的点击事件
                // 编写您想要执行的代码逻辑
                goToTargetActivity(mGroups.getGroupname(),mGroups.getGroupid());
                Toast.makeText(context, "连接", Toast.LENGTH_SHORT).show();
            }
        });
        // 设置点击监听器
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击列表项的逻辑
                // 示例代码：显示一个Toast消息
                Toast.makeText(context, "Clicked item at position: " + position, Toast.LENGTH_SHORT).show();
            }
        });
        return convertView;
    }

    static class ViewHolder {
        TextView groupnameTextView;
        TextView groupidTextView;
        TextView membersAmountTextView;
        ImageView Del;
        ImageView Connect;
    }

    public void goToTargetActivity(String whoName,String groupId) {
        // 创建 Intent
        Intent intent = new Intent(context, GroupTalkingActivity.class);
        // 传递数据（可选）
        intent.putExtra("groupName", whoName);
        intent.putExtra("groupid", groupId);
        // 启动 Activity
        context.startActivity(intent);
    }
}
